<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="false"
    :okAuth="'rd:rd10:rdrecord10:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="70%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #rdrecords10List>
        <!-- <a-button class="mb-2" @click="handleRdrecords10Add" v-auth="'rd:rd10:rdrecord10:edit'">
          <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button> -->
        <BasicTable @register="registerRdrecords10Table" @row-click="handleRdrecords10RowClick" />
       
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsRdRd10Rdrecord10Form">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { Rdrecord10, rdrecord10Save, rdrecord10Form } from '/@/api/wms/rd/rd10/rdrecord10';
  import { companyTreeData } from '/@/api/sys/company';
  import { basWarehouseTreeData } from '/@/api/bas/house/basWarehouse';
  import { Table } from 'ant-design-vue';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('rd.rd10.rdrecord10');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<Rdrecord10>({} as Rdrecord10);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增入库任务单') : t('编辑入库任务单'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('公司名称'),
      field: 'companyCode',
      fieldLabel: 'companyName',
      component: 'TreeSelect',
      componentProps: {
        api: companyTreeData,
        allowClear: true,
      },
      required: true, 
      dynamicDisabled: true,
    },
    {
      label: t('单据编号'),
      field: 'fbillno',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    {
      label: t('数据来源'),
      field: 'sourceFlag',
      component: 'Select',
      componentProps: {
        dictType: 'bas_source_type',
      },
      dynamicDisabled: true,
    },
    {
      label: t('红蓝标志'),
      field: 'bred',
      component: 'Select',
      componentProps: {
        dictType: 'wms_bred_status',
      },
      required: true,
      dynamicDisabled: true,
    },
    {
      label: t('单据日期'),
      field: 'fdate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        showTime: false,
      },
      required: true,
      dynamicDisabled: true,
    },
    // {
    //   label: t('业务类型'),
    //   field: 'ftype',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 64,
    //   },
    // },
    // {
    //   label: t('采购方式'),
    //   field: 'fpomode',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 100,
    //   },
    // },
    // {
    //   label: t('供应商内码'),
    //   field: 'fsupplyid',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 64,
    //   },
    // },
    {
      label: t('供应商名称'),
      field: 'fsuppliername',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
      dynamicDisabled: true,
    },
    {
      label: t('供应商编码'),
      field: 'fsupplierno',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    
    {
      label: t('备注'),
      field: 'fexplanation',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      colProps: { lg: 24, md: 24 },
      dynamicDisabled: true,
    },
    {
      label: t('入库明细'),
      field: 'rdrecords10List',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'rdrecords10List',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 8, md: 24 },
  });

  const [registerRdrecords10Table, rdrecords10Table] = useTable({
    // actionColumn: {
    //   width: 60,
    //   actions: (record: Recordable) => [
    //     {
    //       icon: 'i-ant-design:delete-outlined',
    //       color: 'error',
    //       popConfirm: {
    //         title: '是否确认删除',
    //         confirm: handleRdrecords10Delete.bind(this, record),
    //       },
    //       auth: 'rd:rd10:rdrecord10:edit',
    //     },
    //   ],
    // },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
    showCustomSummary: true,
  });

  async function setRdrecords10TableData(_res: Recordable) {
    rdrecords10Table.setColumns([
      // {
      //   title: t('行号'),
      //   dataIndex: 'fentryid',
      //   width: 130,
      //   align: 'left',
      //   editRow: true,
      //   editComponent: 'Input',
      //   editComponentProps: {
      //     maxlength: 20,
      //   },
      //   editRule: false,
      // },
      // {
      //   title: t('物料内码'),
      //   dataIndex: 'fitemid',
      //   width: 130,
      //   align: 'left',
      //   editRow: true,
      //   editComponent: 'Input',
      //   editComponentProps: {
      //     maxlength: 64,
      //   },
      //   editRule: false,
      // },
      {
        title: t('物料代码'),
        // dataIndex: 'fitemno',
        dataIndex: 'basInv.viewCode',
        width: 130,
        align: 'left',
        
      },
      {
        title: t('物料名称'),
        dataIndex: 'fitemname',
        width: 180,
        align: 'left',
        
      },
       {
        title: t('形象刊'),
        dataIndex: 'freeVO.cfree1',
        width: 100,
        align: 'left',
        
      },
      
      {
        title: t('仓库名称'),
        dataIndex: 'fstockname',
        // dataIndex: 'fstockid',
        // dataLabel: 'fstockname',
        width: 100,
        align: 'left',
        
      },
      {
        title: t('应收数量'),
        dataIndex: 'fqty',
        width: 80,
        align: 'center',
        showSummary: true,
       
      },
      {
        title: t('实收数量'),
        dataIndex: 'sumRkQty',
        width: 80,
        align: 'center',
        showSummary: true,
      },
      
      {
        title: t('行备注'),
        dataIndex: 'fremarks',
        width: 130,
        align: 'left',
      },
    ]);
    rdrecords10Table.setTableData(record.value.rdrecords10List || []);
  }

  function handleRdrecords10RowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleRdrecords10Add() {
    rdrecords10Table.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleRdrecords10Delete(record: Recordable) {
    rdrecords10Table.deleteTableDataRecord(record);
  }

  async function getRdrecords10List() {
    let rdrecords10ListValid = true;
    let rdrecords10List: Recordable[] = [];
    for (const record of rdrecords10Table.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        rdrecords10ListValid = false;
      }
      rdrecords10List.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of rdrecords10Table.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      rdrecords10List.push({
        ...record,
        status: '1',
      });
    }
    if (!rdrecords10ListValid) {
      throw { errorFields: [{ name: ['rdrecords10List'] }] };
    }
    return rdrecords10List;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await rdrecord10Form(data);
    record.value = (res.rdrecord10 || {}) as Rdrecord10;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setRdrecords10TableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.rdrecords10List = await getRdrecords10List();
      // console.log('submit', params, data, record);
      const res = await rdrecord10Save(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }


  const totalSumRkQty = computed(() => {
    const tableData = rdrecords10Table.getDataSource();
    let sum = tableData.reduce((total, item) => total + (item.sumRkQty || 0), 0);
    sum = sum.toFixed(2)
    return sum;
  });

  const totalFqty = computed(() => {
    // 计算总报工数
    const tableData = rdrecords10Table.getDataSource();
    let sum = tableData.reduce((total, item) => total + (item.fqty || 0), 0);
    return sum;
  });
</script>
